package com.choudou5.solr.framework.util;

import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.framework.constants.UserConsts;
import com.choudou5.solr.util.CookieUtil;
import com.choudou5.solr.util.IpUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LFUCache;

import javax.servlet.http.HttpServletRequest;

/**
 * @Name：系统安全 工具类
 * @@author choudou5
 * @@date 2018-07-15
 */
public class SysSecurityUtil {

    private static final String[] IP_WHITE_LIST = new String[]{};//ConfigUtil.getSolrIpWhiteList();

    /**
     * 是否 为内部请求
     * @param request
     * @return
     */
    public static boolean isInnerRequest(HttpServletRequest request) {
        boolean isInnerReq = false;
        String ak = CookieUtil.getCookie(request, "ak");
        if(StrUtil.isNotBlank(ak)){
            // ak + 时间戳 校验有效性
            //ak一致 并且内网
//            if(AK.equals(ak) && isInnerIp(request)){
//                isInnerReq = true;
//            }
        }
        return isInnerReq;
    }

    /**
     * 是否 为管理页面
     * @param request
     * @return
     */
    public static boolean isAdminPage(HttpServletRequest request) {
        String url = RequestUtil.getReqUrl(request);
        return url.startsWith(SysConsts.PAGE_ADMIN_CONSOLE_PREFIX);
    }

    public static boolean isInnerIp(HttpServletRequest request) {
        boolean isInnerIp = false;
        String ip = IpUtil.getRealIpAddr(request);
        for (String whiteIp : IP_WHITE_LIST) {
            if(ip.startsWith(whiteIp)){
                isInnerIp = true;
                break;
            }
        }
        return isInnerIp;
    }

    private static final LFUCache<String, String> ACCESS_STAT = CacheFactory.newLFUCache(UserConsts.MAX_ONLINE, 10 * 1000); //10秒有效期

    /**
     * 检查是否 是安全的访问
     * @param req
     * @return
     */
    public static boolean checkSafeAccess(HttpServletRequest req){
        String ip = IpUtil.getRealIpAddr(req);
        String url = RequestUtil.getReqUrl(req);
        //跳过 搜索接口
        if("/adminConsole/searchOptimize/pageList".equals(url)
            || "/adminConsole/searchOptimize/search".equals(url)
            || "/adminConsole/system/lastNotice".equals(url)){
            return true;
        }
        String cache = ACCESS_STAT.get(ip);
        if(cache == null){
            ACCESS_STAT.put(ip, "1");
        }else{
            long accessCount = ACCESS_STAT.getAccessCount(ip);
            LogDeBugUtil.debug(ip + " accessCount:" + accessCount);
            if(accessCount > 20){ //10秒了最多请求20次
                return false;
            }
        }
        return true;
    }


}
